package org.doyutu.controller;

import org.doyutu.config.DiscoveryClientProperty;
import org.doyutu.service.FeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

/**
 * @author doyutu
 * @email 859898972@qq.com
 * @date 2018-06-28 21:47
 * org.doyutu.controller
 */
@RestController
public class FeignController {

    @Autowired
    private FeignService feignService;

    @Autowired
    private LoadBalancerClient client;

    @Autowired
    @Qualifier(value = "restTemplate")
    private RestTemplate restTemplate;

    @Autowired
    @Qualifier(value = "loadBalanceRestTemplate")
    private RestTemplate loadBalanceRestTemplate;

    @Autowired
    private WebClient webClient;

    @Autowired
    private DiscoveryClientProperty discoveryClientProperty;

    @RequestMapping("/loadBalancerHome")
    public String loadBalancerHome() {
        ServiceInstance instance = client.choose(discoveryClientProperty.getName());
        String url = String.format("http://%s:%s/", instance.getHost(), instance.getPort());
        return "loadBalance:" + restTemplate.getForObject(url, String.class);
    }

    @RequestMapping("/restLoadBalancerHome")
    public String restLoadBalancerHome() {
        String url = String.format("http://%s", discoveryClientProperty.getName());
        String result = loadBalanceRestTemplate.getForObject(url, String.class);
        return "restLoadBalance:" + result;
    }

    @RequestMapping("/feignLoadBalanceHome")
    public String home() {
        return "feignLoadBalance:" + feignService.home();
    }

    @RequestMapping("/webFluxLoadBalance")
    public Mono<String> webFluxLoadBalance() {
        return webClient.get()
                .uri("/discovery/client")
                .retrieve()
                .bodyToMono(String.class);
    }

}
